package com.zlyx.easy.http.handlers;

import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;

import com.zlyx.easy.core.buffer.EasyBuffer;
import com.zlyx.easy.core.handler.annotations.Brancher;
import com.zlyx.easy.core.utils.StringUtils;
import com.zlyx.easy.http.executor.HttpExecutor;
import com.zlyx.easy.http.models.RequestModel;

/**
 * 
 * @Auth 赵光
 * @Describle
 * @2019年12月25日
 */
@Brancher(todo = { "处理GET请求" }, value = "GET")
public class GetMappingHandler extends AbstractMappingHandler {

	public GetMappingHandler(@Autowired(required = false) HttpExecutor httpService) {
		super(httpService);
	}

	@Override
	public Object handleMapping(RequestModel rm) throws Exception {
		EasyBuffer eb = EasyBuffer.newBuffer("?");
		String url = rm.getUrl();
		if (rm.getParams() != null) {
			for (Entry<String, Object> entry : rm.getParams().entrySet()) {
				String key = entry.getKey();
				String value = StringUtils.valueOf(entry.getValue());
				if (url.contains(":" + key)) {
					url = url.replace(":" + key, "" + value);
				} else if (url.contains("{" + key + "}")) {
					url = url.replace("{" + key + "}", "" + value);
				} else {
					eb.append(key).append("=").append(value).append("&");
				}
			}
			if (!url.contains("?") && !"?".equals(eb.toString())) {
				url += eb.clearEnd();
			}
		}
		return httpService.excute(rm, url, null, rm.getReturnType());
	}

}
